/*
 * @Date: 2022-03-29 12:58:38
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-04-12 09:03:06
 * @FilePath: /payment/pay/src/pages/PayGroundCard/PayGroundCardset.jsx
 */
import React, { useState, useEffect, useRef } from "react";
import zhCN from "antd/es/locale/zh_CN";
import {
  Row,
  Col,
  Button,
  Table,
  Input,
  Modal,
  Form,
  ConfigProvider,
} from "antd";
import Tab from "../../components/Tabs";
import "./Card.css";
import "./configuration.css";
import { SearchOutlined } from "@ant-design/icons";
import { type } from "@testing-library/user-event/dist/type";
import axios from "axios";
import {
  getCard,
  getCardsearch,
  getCardPremata,
  postCardCredact,
  postCardAddbtn,
  postCardDelcfg,
} from "./../../API/PayCard";
export default function PayGroundCardset() {
  //判断按钮
  const [addbtn, setaddbtn] = useState(null);
  //表单绑定
  const [form] = Form.useForm();
  //总条数
  const [total, settotal] = useState(6);
  //点击行改变样式
  const [keycss, setkeycss] = useState(15);
  //搜索框value值
  const Search = useRef(null);
  //每页条数
  const [pageSize, setpageSize] = useState(5);
  //删除数组
  const [Del, setDel] = useState([]);
  //控制新增、编辑modal
  const [visible, setVisible] = useState(false);
  //控制radio的选中状态
  const [ridio, setRidio] = useState(null);
  //商户...数组
  const [CardData, setCardData] = useState([]);
  //点击商户的已有支付配置数组
  const [Predata, setPredata] = useState([]);
  useEffect(() => {
    //初始化调接口
    CardPort(pageSize, 1);
    //Premata(keycss);
  }, []);
  //表单绑定ref
  const formRef = useRef();
  //卡商列表接口函数
  const CardPort = (limit, page) => {
    getCard({ limit: limit, page: page })
      /*   axios({
      url: "http://139.155.90.63:8080/admin/sh_peiZhi/selectAllShangHu",
      method: "get",
      params: { limit: limit, page: page },
    }) */
      .then((res) => {
        //console.log(res.data);
        let arr = [];
        if (res.code === 0) {
          res.data.map((item, index) => {
            //console.log(item);
            let obj = {
              key: item.id,
              // keyid:index,
              CardId: item.yongHuId,
              CardName: item.nickName,
              UserName: item.name,
            };
            arr.push(obj);
          });
          //Premata(arr[0].key);
          settotal(res.count);
          setCardData(arr);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  //商户的已有支付配置接口
  const Premata = (id) => {
    console.log(id);
    getCardPremata({ userId: id, userId: id })
      /*  axios({
      url: "http://172.16.106.186:8080/admin/sh_peiZhi/selectAllFeiLvConfig",
      method: "get",
      params: { userId: id, userId: id },
    }) */
      .then((res) => {
        console.log(res);
        let arr = [];
        if (res.code === 0) {
          res.data.map((item, index) => {
            let obj = {
              key: item.id,
              Id: item.id,
              min: item.tiXianMin,
              max: item.tiXianMax,
              money: item.tiXianShouXu,
              rate: item.tiXianFeiLv,
            };
            arr.push(obj);
          });
          //console.log(arr);
          setPredata(arr);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  //查询按钮接口
  const CardSearch = () => {
    console.log(pageSize);
    getCardsearch({
      condition: Search.current.input.value,
      limit: total,
      page: 1,
    })
      /*  axios({
      url: "http://172.16.106.186:8080/admin/sh_peiZhi/selectByCondition",
      method: "get",
      params: {
        condition: Search.current.input.value,
        limit: pageSize,
        page: 1,
      },
    }) */
      .then((res) => {
        console.log(res);
        let arr = [];
        if (res.code === 0) {
          res.data.map((item, index) => {
            //console.log(item);
            let obj = {
              key: item.id,
              CardId: item.yongHuId,
              CardName: item.nickName,
              UserName: item.name,
            };
            arr.push(obj);
          });
          setCardData(arr);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  //编辑接口
  const Credact = (max, min, money, rate) => {
    postCardCredact({
      id: Del[0].Id,
      tiXianFeiLv: rate,
      tiXianMax: max,
      tiXianMin: min,
      tiXianShouXu: money,
    })
      /* axios({
      url: "http://172.16.106.186:8080/admin/sh_peiZhi/updFeiLvConfig",
      method: "post",
      data: {
        id: Del[0].Id,
        tiXianFeiLv: rate,
        tiXianMax: max,
        tiXianMin: min,
        tiXianShouXu: money,
      },
      headers: {
        "Content-Type": "application/json",
      },
    }) */ .then((res) => {
        console.log(res);
        Premata(keycss);
      });
  };
  //新增接口
  const Addbtn = (max, min, money, rate) => {
    postCardAddbtn({
      tiXianFeiLv: rate,
      tiXianMax: max,
      tiXianMin: min,
      tiXianShouXu: money,
      userId: keycss,
    })
      /*  axios({
      url: "http://172.16.106.186:8080/admin/sh_peiZhi/addFeiLvConfig",
      method: "post",
      data: {
        tiXianFeiLv: rate,
        tiXianMax: max,
        tiXianMin: min,
        tiXianShouXu: money,
        userId: keycss,
      },
      headers: {
        "Content-Type": "application/json",
      },
    }) */ .then((res) => {
        console.log(res);
        Premata(keycss);
      });
  };
  //删除当前选定的支付配置接口
  const Delcfg = (id) => {
    postCardDelcfg({ id: id })
      /*  axios({
      url: "http://172.16.106.186:8080/admin/sh_peiZhi/delFeiLvConfig",
      method: "post",
      params: { id: id },
    }) */
      .then((res) => {
        Premata(keycss);
        setRidio(null);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  //商户表格函数
  const Pagechange = (pagination) => {
    console.log(pagination);
    setpageSize(pagination.pageSize);
    CardPort(pageSize, pagination.current);
  };

  //清空输入框内容时
  const CardEmpty = () => {
    if (Search.current.input.value.length == 0) {
      CardPort(pageSize, 1);
    }
  };

  //点击行
  const RowClick = (record, index) => {
    console.log(record, index);
    setkeycss(record.key);
    //调用支付配置接口
    Premata(record.key);
  };
  //表单提交按钮
  const onSubmit = () => {
    console.log(addbtn);
    if (addbtn === null) {
      //编辑接口
      form.validateFields().then((values) => {
        form.resetFields();
        console.log(values);
        Credact(
          values.PaidAmountMin,
          values.PaidAmountMax,
          values.CommissionCharge,
          values.PaidRate
        );
      });
    } else {
      //新增接口
      form.validateFields().then((values) => {
        form.resetFields();
        console.log(values);
        Addbtn(
          values.PaidAmountMin,
          values.PaidAmountMax,
          values.CommissionCharge,
          values.PaidRate
        );
      });
    }
    setVisible(false);
  };

  //控制radio选中后操作控制modal编辑按钮
  const redact = () => {
    ridio === null ? setVisible(false) : setVisible(true);
    setaddbtn(null);
    if (ridio !== null) {
      form.validateFields().then((values) => {
        form.resetFields();
        console.log(values);

        //表单赋值
        formRef.current.setFieldsValue({
          PaidAmountMin: Del[0].min,
          PaidAmountMax: Del[0].max,
          CommissionCharge: Del[0].money,
          PaidRate: Del[0].rate,
        });
      });
    }
  };
  //控制modal新增按钮
  const added = () => {
    setVisible(true);
    form.validateFields().then((values) => {
      form.resetFields();
      //表单重置
      formRef.current.setFieldsValue({
        PaidAmountMin: "",
        PaidAmountMax: "",
        CommissionCharge: "",
        PaidRate: "",
      });
    });
    setaddbtn(1);
  };
  //控制删除modal
  const [visibletwo, setvisibletwo] = useState(false);
  //点击单选框
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setRidio(selectedRows);
      setDel(selectedRows);
      console.log(selectedRows);
    },
  };
  //删除按钮
  const DelConfig = () => {
    //console.log(record);
    console.log(Del);
    ridio === null ? setvisibletwo(false) : setvisibletwo(true);
  };
  //删除modal下的确定按钮
  const DelConfirm = () => {
    Delcfg(Del[0].Id);
    setvisibletwo(false);
  };
  //商户号...表头
  const columns = [
    {
      title: "商户号",
      width: 150,
      dataIndex: "CardId",
      key: "CardId",
    },
    {
      title: "商户名称",
      width: 150,
      dataIndex: "CardName",
      key: "CardName",
    },
    { title: "用户名", width: 100, dataIndex: "UserName", key: "UserName" },
  ];
  //代付类型名称表头
  const Nametype = [
    {
      title: "代付类型名称",
      width: 150,
      dataIndex: "Disbursementtype",
      key: "Disbursementtype",
    },
  ];
  //代付类型名称数组
  const Typedata = [
    {
      key: "Disbursementtype",
      Disbursementtype: "手动银行卡",
    },
  ];
  //金额...表头
  const Prname = [
    {
      title: "金额(最小)",
      width: 150,
      dataIndex: "min",
      key: "min0",
    },
    {
      title: "金额(最大)",
      width: 150,
      dataIndex: "max",
      key: "max",
    },
    {
      title: "手续费(元)",
      width: 150,
      dataIndex: "money",
      key: "money",
    },
    {
      title: "费率(%)",
      width: 150,
      dataIndex: "rate",
      key: "rate",
    },
  ];
  return (
    <div>
      <Modal
        title="添加代付配置"
        centered
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        width={1200}
        footer={[
          <Row key="Spay">
            <Col span={10}></Col>
            <Col span={2} className="F-btn">
              <Button
                key="Paysub"
                type="primary"
                size="large"
                onClick={onSubmit}
              >
                提交
              </Button>
            </Col>
            <Col span={2} className="F-btn">
              <Button
                key="Paybtn"
                type="primary"
                size="large"
                onClick={() => setVisible(false)}
              >
                返回
              </Button>
            </Col>
          </Row>,
        ]}
      >
        <Row>
          <Col span={1}></Col>
          <Col span={22} className="config-title">
            基本信息
          </Col>
          <Col span={1}></Col>
        </Row>
        <Form
          form={form}
          className="config-form"
          ref={formRef}
          labelCol={{ span: 18 }}
          wrapperCol={{ span: 14 }}
          layout="inline"
        >
          <Form.Item
            layout="inline"
            label="代付金额(最小)"
            name="PaidAmountMin"
            style={{ marginLeft: 40 }}
            //rules={[{ required: true, message: "输入的密码格式错误" }]}
          >
            <Input
              size="large"
              placeholder="请输入代付最小金额"
              style={{ width: 240 }}
            />
          </Form.Item>
          <Form.Item
            label="代付金额(最大)"
            name="PaidAmountMax"
            style={{ marginLeft: 45 }}
            // rules={[{ required: true, message: "重复输入的密码格式错误" }]}
          >
            <Input
              size="large"
              placeholder="请输入代付最大金额"
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item
            label="代付手续费(元/笔)"
            name="CommissionCharge"
            style={{ marginTop: 35, marginLeft: 40 }}
            // rules={[{ required: true, message: "输入的密码格式错误" }]}
          >
            <Input
              size="large"
              placeholder="请输入代付手续费(元/笔)"
              style={{ width: 220 }}
            />
          </Form.Item>
          <Form.Item
            label="代付费率(%/笔)"
            name="PaidRate"
            style={{ marginTop: 35, marginLeft: 45 }}

            // rules={[{ required: true, message: "重复输入的密码格式错误" }]}
          >
            <Input
              size="large"
              placeholder="请输入代付费率(%笔)"
              style={{ width: 197 }}
            />
          </Form.Item>
        </Form>
        {/* 删除modal */}
      </Modal>
      <Modal
        title="信息"
        centered
        className="Modaltwo"
        visible={visibletwo}
        onCancel={() => setvisibletwo(false)}
        width={600}
        footer={[
          <Row key="Delse">
            <Col span={6}></Col>
            <Col span={6} className="F-btn">
              <Button
                key="Delsure"
                onClick={DelConfirm}
                type="primary"
                size="large"
              >
                确定
              </Button>
            </Col>
            <Col span={6} className="F-btn">
              <Button
                onClick={() => setvisibletwo(false)}
                type="primary"
                size="large"
                key="Delrtn"
              >
                返回
              </Button>
            </Col>
          </Row>,
        ]}
      >
        <Row>
          <Col
            span={24}
            style={{
              height: "80px",
              lineHeight: "80px",
              textAlign: "center",
            }}
          >
            是否删除代付配置
          </Col>
        </Row>
      </Modal>
      <Tab title={"商户配置"}></Tab>
      <Row>
        <Col span={8} className="Cl-css">
          <Row className="Input-one">
            <Col span={12}>
              <Input
                size="large"
                type="text"
                placeholder="商户账户/商户名称/商户号"
                ref={Search}
                onChange={CardEmpty}
              />
            </Col>
            <Col span={1}></Col>
            <Col span={6} className="Button-icon">
              <Button
                className="green"
                size="large"
                type="primary"
                icon={<SearchOutlined />}
                onClick={CardSearch}
              >
                搜索
              </Button>
            </Col>
          </Row>
          <Row style={{ marginTop: "20px" }}>
            <Col>
              <ConfigProvider locale={zhCN}>
                <Table
                  bordered
                  className="Fconfiguration"
                  columns={columns}
                  dataSource={CardData}
                  onChange={Pagechange}
                  pagination={{
                    total: total,
                    pageSize: pageSize,
                    pageSizeOptions: [5, 10, 20, 50, 100],
                    showQuickJumper: true,
                  }}
                  onRow={(record, index) => {
                    return {
                      onClick: () => {
                        RowClick(record, index);
                      },
                    };
                  }}
                  rowClassName={(record) => {
                    return record.key === keycss ? "clickRowStyl" : null;
                  }}
                  scroll={{ x: 400, y: 450 }}
                  sticky={true}
                />
              </ConfigProvider>
            </Col>
          </Row>
        </Col>
        <Col span={4} className="Cl-css">
          <Table
            className="configuration"
            columns={Nametype}
            pagination={false}
            dataSource={Typedata}
            rowClassName="clickRowStyl"
          />
        </Col>
        <Col span={12} className="Cl-css">
          <Row className="configuration-right">
            <Col span={4}>
              <Button
                className="green"
                size="large"
                type="primary"
                icon={<SearchOutlined />}
                onClick={added}
              >
                新增
              </Button>
            </Col>
            <Col span={4}>
              <Button
                className="green"
                size="large"
                type="primary"
                icon={<SearchOutlined />}
                onClick={redact}
              >
                编辑
              </Button>
            </Col>
            <Col span={4}>
              <Button
                className="green"
                size="large"
                type="primary"
                icon={<SearchOutlined />}
                onClick={DelConfig}
              >
                删除
              </Button>
            </Col>
          </Row>
          <Row>
            <Col>
              <Table
                className="Tconfiguration"
                columns={Prname}
                pagination={false}
                dataSource={Predata}
                rowSelection={{
                  type: "radio",
                  ...rowSelection,
                }}
              />
            </Col>
          </Row>
        </Col>
      </Row>
    </div>
  );
}
